﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace RefreshDataClient
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            InitEvent();
        }
        public void InitEvent()
        {
            btnPurchase.Click += (s, e) => 
            {
                string sql = $@"select 
Id=main.FID
,billNo=main.FBILLNO
,entyId=enty.FENTRYID
,unitId=enty.FUNITID --采购单位Id
,priceUnitId=entyF.FPRICEUNITID --计价单位Id
,matId=mat.FMATERIALID --物料ID
,matNumber=mat.FNUMBER
,price=entyF.FPRICE
,isFree=enty.FGIVEAWAY --是否赠品
,taxPrice=entyF.FTAXPRICE --含税单价
,taxRate=entyF.FTAXRATE --税率
,discountRate=entyF.FDISCOUNTRATE --折扣率
,qty=enty.FQTY --采购数量
,allAmount=entyF.FALLAMOUNT  --价税合计
,amount=entyF.FAMOUNT --金额
,taxAmount=entyF.FTAXAMOUNT --税额
,discountAmount=entyF.FDISCOUNT --折扣额
from t_PUR_POOrderEntry enty
inner join T_PUR_POORDERENTRY_F entyF on enty.FENTRYID=entyF.FENTRYID
inner join t_PUR_POOrder main on enty.FID=main.FID
left join T_BD_MATERIAL mat on enty.FMATERIALID=mat.FMATERIALID";
                DataTable dt = DBHelper.GetDataTable(sql);
                List<PurData> dataList = dt.ToDataList<PurData>();
                if (dataList.Count < 1)
                    return;
                List<string> sqlList = new List<string>();
                var dataDic = dataList.GroupBy(x => x.billNo).ToDictionary(y => y.Key, y => y.ToList());
                foreach (var dic in dataDic)
                {
                    PurData firstData = dic.Value.FirstOrDefault();
                    //List<int> entyids = dic.Value.Select(x => x.entyId).Distinct().ToList();
                    int seq = 1;
                    List<PurData> valuedatas = dic.Value.GroupBy(x => new { x.matNumber, x.taxPrice, x.taxRate, x.discountRate, x.isFree }).Select(x =>
                    {
                        PurData fpur = x.FirstOrDefault();
                        fpur.qty = x.Sum(a => a.qty);
                        fpur.allAmount = x.Sum(a => a.allAmount);
                        fpur.amount = x.Sum(a => a.amount);
                        fpur.taxAmount = x.Sum(a => a.taxAmount);
                        fpur.discountAmount = x.Sum(a => a.discountAmount);
                        fpur.seq = seq++;
                        return fpur;
                    }).ToList();
                    try
                    {
                        List<string> sqls = valuedatas.Select(x => $@"/*dialect*/ insert into RLKX_t_Cust_MXHZXX
(FID
,FSeq
,F_RLKX_WLBM  --物料编码
,F_RLKX_CGDW  --采购单位
,F_RLKX_JJDW  --计价单位
,F_RLKX_CGSL  --采购数量
,F_RLKX_JJSL  --计价数量
,F_RLKX_PRICE  --单价
,F_RLKX_HSPRICE --含税单价
,F_RLKX_JE  --金额
,F_RLKX_DISCOUNTRATE_6LR  --折扣率
,F_RLKX_DISCOUNT_8ZB  --折扣额
,F_RLKX_SL  --税率
,F_RLKX_SE  --税额
,F_RLKX_JSHJ  --价税合计
,F_RLKX_SFZP  --是否赠品
)
values(
{x.Id}
,{x.seq}
,{x.matId}
,{x.unitId}
,{x.priceUnitId}
,{x.qty}
,{x.qty}
,{x.price}
,{x.taxPrice}
,{x.amount}
,{x.discountRate}
,{x.discountAmount}
,{x.taxRate}
,{x.taxAmount}
,{x.allAmount}
,{x.isFree}
)
").ToList();
                        sqlList.AddRange(sqls);
                    }
                    catch (Exception ex)
                    {
                        continue;
                    }

                }
                string sqlStr = string.Join(";", sqlList);
                LogHelper.WriteLog(sqlStr,"采购订单");
            };
            btnDirectAllot.Click += (s, e) => 
            {
                string sql = $@"select 
Id=main.FID
,billNo=main.FBILLNO
,entyId=enty.FENTRYID
,unitId=enty.FUNITID --采购单位Id
,matId=mat.FMATERIALID --物料ID
,matNumber=mat.FNUMBER
,qty=enty.FQTY --数量
from T_STK_STKTRANSFERINENTRY enty
inner join T_STK_STKTRANSFERIN main on enty.FID=main.FID
left join T_BD_MATERIAL mat on enty.FSRCMATERIALID=mat.FMATERIALID";
                DataTable dt = DBHelper.GetDataTable(sql);
                List<PurData> dataList = dt.ToDataList<PurData>();
                if (dataList.Count < 1)
                    return;
                List<string> sqlList = new List<string>();
                var dataDic = dataList.GroupBy(x => x.billNo).ToDictionary(y => y.Key, y => y.ToList());
                foreach (var dic in dataDic)
                {
                    PurData firstData = dic.Value.FirstOrDefault();
                    int seq = 1;
                    List<PurData> valuedatas = dic.Value.GroupBy(x => x.matId).Select(x =>
                    {
                        PurData fpur = x.FirstOrDefault();
                        fpur.qty = x.Sum(a => a.qty);
                        fpur.seq = seq++;
                        return fpur;
                    }).ToList();
                    try
                    {
                        List<string> sqls = valuedatas.Select(x => $@"/*dialect*/ insert into RLKX_t_Cust_WLHZMX
(FID
,FSeq
,F_RLKX_WLBM  --物料编码
,F_RLKX_JLDW  --计量单位
,F_RLKX_DBSL  --数量
)
values(
{x.Id}
,{x.seq}
,{x.matId}
,{x.unitId}
,{x.qty}
)
").ToList();
                        sqlList.AddRange(sqls);
                    }
                    catch (Exception ex)
                    {
                        continue;
                    }

                }
                string sqlStr = string.Join(";", sqlList);
                LogHelper.WriteLog(sqlStr, "直接调拨单");
            };
            btnDeletePurchase.Click += (s, e) => 
            {
                string sql = $@"select FID from t_PUR_POOrder";
                DataTable dt = DBHelper.GetDataTable(sql);
                List<int> Ids = dt.Rows.Cast<DataRow>().Select(x => x["FID"].ToStringV1().ToInt32V1()).ToList();
                string sqlStr = $@"delete from RLKX_t_Cust_MXHZXX where FID in ({string.Join(",",Ids)})";
                LogHelper.WriteLog(sqlStr, "采购订单删除脚本");
            };
            btnDeleteDirectAllot.Click += (s, e) =>
            {
                string sql = $@"select FID from T_STK_STKTRANSFERIN";
                DataTable dt = DBHelper.GetDataTable(sql);
                List<int> Ids = dt.Rows.Cast<DataRow>().Select(x => x["FID"].ToStringV1().ToInt32V1()).ToList();
                string sqlStr = $@"delete from RLKX_t_Cust_WLHZMX where FID in ({string.Join(",", Ids)})";
                LogHelper.WriteLog(sqlStr, "直接调拨单删除脚本");
            };
        }
        public static void WSLog(string BillNo, string Msg, string Msg1, bool status, string btype)
        {
            try
            {
                string sql = $@"insert into WSLog(BillNo,Msg,Msg1,[status],btype)
values(@BillNo,@Msg,@Msg1,'{status}',@btype)";
                DBHelper.ExecuteNonQuery(sql,new System.Data.SqlClient.SqlParameter[] { 
                   new System.Data.SqlClient.SqlParameter("@BillNo",BillNo.ToStringV1()),
                   new System.Data.SqlClient.SqlParameter("@Msg",Msg.ToStringV1()),
                   new System.Data.SqlClient.SqlParameter("@Msg1",Msg1.ToStringV1()),
                   new System.Data.SqlClient.SqlParameter("@btype",btype.ToStringV1()),
                });
            }
            catch (Exception) { }
        }
    }
    public class PurData
    {
        public int Id { get; set; }
        public int seq { get; set; }
        public string billNo { get; set; }
        public int entyId { get; set; }
        public int unitId { get; set; }
        public int priceUnitId { get; set; }
        public int matId { get; set; }
        public string matNumber { get; set; }
        public decimal price { get; set; }
        public int isFree { get; set; }
        public decimal taxPrice { get; set; }
        public decimal taxRate { get; set; }
        public decimal discountRate { get; set; }

        public decimal qty { get; set; }
        public decimal allAmount { get; set; }
        public decimal amount { get; set; }
        public decimal taxAmount { get; set; }
        public decimal discountAmount { get; set; }

    }
}
